package com.expense.app.admin.services.job.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.expense.app.admin.common.BaseService;
import com.expense.app.admin.model.dto.job.JobDTO;
import com.expense.app.admin.model.dto.job.JobImportDTO;
import com.expense.app.admin.model.dto.job.JobListDTO;
import com.expense.app.admin.model.dto.job.JobPageDTO;
import com.expense.app.admin.model.params.job.JobImportParam;
import com.expense.app.admin.model.params.job.mengniu.JobListParam;
import com.expense.app.admin.model.params.job.mengniu.JobParam;
import com.expense.app.admin.services.job.MengniuJobServ;
import com.expense.common.constant.enums.DeletedStatus;
import com.expense.common.dao.job.MengniuJobCityDao;
import com.expense.common.dao.job.MengniuJobDao;
import com.expense.common.entity.params.SortParam;
import com.expense.common.exception.PlatformException;
import com.expense.common.model.auth.AdminUser;
import com.expense.common.model.job.MengniuJob;
import com.expense.common.model.job.MengniuJobCity;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 招聘岗位
 */
@Service
public class MengniuJobServImpl extends BaseService implements MengniuJobServ {
    private static final Log log = LogFactory.get();

    @Autowired
    MengniuJobDao mengniuJobDao;
    @Autowired
    MengniuJobCityDao mengniuJobCityDao;

    @Override
    public JobListDTO findList(JobListParam param) {
        Map<String,Object> condition = new HashMap<>();
        condition.put("key",param.getKey());
//        condition.put("project",param.getProject()); // 蒙牛 不再按照项目查询列表,防止反复,暂时注释 2019-09-20 08:40
        String city = param.getCity();
        if(StrUtil.isNotBlank(city)){
            condition.put("citys",city.split("_"));
        }
        String jobType = param.getJobType();
        if(StrUtil.isNotBlank(jobType)){
            condition.put("jobTypes",jobType.split("_"));
        }
        PageQuery pageQuery = initPageQuery(param.getPage(),param.getSort(), new SortParam("sort",SortParam.ASC));
        pageQuery.setParas(condition);
        mengniuJobDao.findListPage(pageQuery);
        return new JobListDTO(pageQuery.getList(), pageQuery.getTotalRow());
    }

    @Override
    public JobPageDTO findInitList(String project) {
        List<String> jobTypeList = mengniuJobDao.findJobTypeList(project);
        List<String> cityList = mengniuJobCityDao.findCityList(project);
        return JobPageDTO.builder().jobTypeList(jobTypeList).cityList(cityList).build();
    }

    @Override
    public MengniuJob findOne(Long id) {
        return mengniuJobDao.findByIdAndDeleted(id);
    }

    @Override
    public JobDTO findDetail(Long id) {
        MengniuJob entity = mengniuJobDao.findByIdAndDeleted(id);
        if(entity != null){
            entity.setJobCityList(mengniuJobCityDao.findByJobId(id));
        }
        return new JobDTO(entity);
    }

    @Override
    public MengniuJob saveOne(JobParam param) {
        MengniuJob entity = param.getEntity();
        setBaseInfo(entity);
        //其他关联处理
        if(null != entity.getId()){
            List<MengniuJobCity> list = entity.getJobCityList();
            MengniuJobCity city = list.get(0);
            setBaseInfo(city);
            city.setCity(entity.getWorkPlace());
            mengniuJobCityDao.saveOne(city);
        }
        mengniuJobDao.saveOne(entity);
        return entity;
    }

    @Override
    public Long deleteOne(Long id) {
        MengniuJob entity = mengniuJobDao.findByIdAndDeleted(id);
        if(entity == null) throw new PlatformException("招聘岗位已不存在");
        entity.setDeleted(DeletedStatus.DELETED);
        setBaseInfo(entity);
        mengniuJobDao.updateTemplateById(entity);
        //其他关联处理
        return id;
    }

    @Override
    @Transactional
    public JobImportDTO importExcel(JobImportParam param) {
        AdminUser loginUser = getCurrentUser();
        List<Map<String,String>> list = param.getMapList();
        List<Map<String,String>> errorList = new ArrayList<>();
        List<Map<String,String>> errorDataList = new ArrayList<>();
        //遍历所有的数据
        if(list != null && list.size()>0) {
            // 清空之前的数据
            if("update".equals(param.getType())){
                mengniuJobDao.deleteAll(loginUser.getId());
                mengniuJobCityDao.deleteAll(loginUser.getId());
            }
            List<MengniuJob> jobList = new ArrayList<>();
            for (Map<String, String> map : list) {
                int index = list.indexOf(map);
                String sort = map.get("序号");
                String project = map.get("项目");
                String jobTitle = map.get("招聘岗位");
                String jobType = map.get("职能名称");
                String jobDesc = map.get("岗位职责");
                String requirement = map.get("任职要求");
                String workPlace = map.get("工作地点");
                String eduDegree = map.get("学历要求");
                String applyUrl = map.get("链接");

                //返回错误记录
                Map<String, String> errorData = new HashMap<>();
                errorData.put("sort", sort);
                errorData.put("project", project);
                errorData.put("jobTitle", jobTitle);
                errorData.put("jobType", jobType);
                errorData.put("jobDesc", jobDesc);
                errorData.put("requirement", requirement);
                errorData.put("workPlace", workPlace);
                errorData.put("eduDegree", eduDegree);
                errorData.put("applyUrl", applyUrl);

                MengniuJob entity = new MengniuJob();
                // 序号不能为空
                if (StrUtil.isBlank(sort)) {
                    String reason = "序号不能为空";
                    errorList.add(genErrorMap(index, "序号", sort, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }
//                if (StrUtil.isBlank(project)) {
//                    String reason = "项目不能为空";
//                    errorList.add(genErrorMap(index, "项目", project, reason));
//                    errorDataList.add(genErrorDataMap(errorData, reason));
//                    continue;
//                }
                if (StrUtil.isBlank(jobTitle)) {
                    String reason = "招聘岗位不能为空";
                    errorList.add(genErrorMap(index, "招聘岗位", jobTitle, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }
                if (StrUtil.isBlank(jobType)) {
                    String reason = "职能名称不能为空";
                    errorList.add(genErrorMap(index, "职能名称", jobType, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }
                if (StrUtil.isBlank(applyUrl)) {
                    String reason = "链接地址不能为空";
                    errorList.add(genErrorMap(index, "链接", applyUrl, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }
                if(StrUtil.isBlank(workPlace)){
                    String reason = "工作地点不能为空";
                    errorList.add(genErrorMap(index,"工作地点",workPlace,reason));
                    errorDataList.add(genErrorDataMap(errorData,reason));
                    continue;
                }

                setBaseInfo(entity);
                entity.setSort(Convert.toInt(sort,99999));
                entity.setProject(project);
                entity.setJobTitle(jobTitle);
                entity.setJobType(jobType);
                entity.setWorkPlace(workPlace);
                entity.setJobDesc(jobDesc);
                entity.setRequirement(requirement);
                entity.setEduDegree(eduDegree);
                entity.setApplyUrl(applyUrl);
                jobList.add(entity);
            }
            if(jobList.size()>0) {
                List<MengniuJobCity> cityList = new ArrayList<>();
                jobList.forEach(job ->{
                    mengniuJobDao.insertTemplate(job,true);

                    MengniuJobCity model = new MengniuJobCity();
                    setBaseInfo(model);
                    model.setJobId(job.getId());
                    String city = job.getWorkPlace();
                    int index = city.lastIndexOf("市");
                    if(index>-1 && index == city.length()-1 ){
                        city = city.substring(0,index);
                    }
                    model.setCity(city);
                    model.setApplyUrl(job.getApplyUrl());
                    cityList.add(model);
                });
                mengniuJobCityDao.saveAll(cityList);
            }
        }
        JobImportDTO dto = new JobImportDTO();
        dto.setTotalCount(list.size());
        dto.setSuccessCount(list.size() - errorList.size());
        dto.setErrorCount(errorList.size());
        dto.setErrorList(errorList);
        dto.setErrorDataList(errorDataList);
        return dto;
    }


    /**
     * 生成错误返回map
     * @param index 错误所在行索引,从0开始
     * @param field 错误列名
     * @param fieldValue 错误列值
     * @param reason 错误说明
     * @return
     */
    public Map<String,String> genErrorMap(Integer index,String field,String fieldValue,String reason){
        Map<String, String> exit = new HashMap<>();
        exit.put("index", (index+1)+"");
        exit.put("field", field);
        exit.put("val",fieldValue);
        exit.put("reason", reason);
        return exit;
    }
    public Map<String,String> genErrorDataMap(Map<String,String> errorData,String reason){
        errorData.put("reason", reason);
        return errorData;
    }
}
